package org.hackystat.devcathlon.ui.page.form.validators;

import java.util.List;
import java.util.Map;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.hackystat.devcathlon.engine.user.User;
import org.hackystat.devcathlon.engine.user.UserManager;

/**
 * Username validator.
 * 
 * @author Anthony Du
 */
public class UserNameValidator extends AbstractValidator {

  /** Support Serialization. */
  private static final long serialVersionUID = 1L;
  /** Boolean for omitting self from validation. */
  private User user;

  /**
   * User name validator constructor.
   */
  public UserNameValidator() {
    // empty constructor.
  }
  
  /**
   * User name validator constructor.
   * 
   * @param user The current user.
   */
  public UserNameValidator(User user) {
    this.user = user;
  }

  /**
   * Validates the given item.
   * 
   * @param validatable
   *          The item to be validated.
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void onValidate(IValidatable validatable) {
    String value = (String) validatable.getValue();
    for (User user : (List<User>) UserManager.getInstance().getUsers()) {
      if (value.equals(user.getUsername()) && !checkUsername(value)) {
        error(validatable);
      }
    }
  }
  
  /**
   * Checks to see if current user has the same username.
   * 
   * @param username The username to compare.
   * @return True if the user has the same name, else false 
   */
  private boolean checkUsername(String username) {
    // ignore current user's username for validation.
    if (null == user) {
      return false;
    }
    if (username.equals(this.user.getUsername())) {
      return true;
    }
    return false;
  }

  /**
   * Specifies the resource key for this validation.
   * 
   * @return The resource key.
   */
  @Override
  protected String resourceKey() {
    return "UserNameValidator";
  }

  /**
   * Validation keys map. This maps the keys associated to the error message.
   * 
   * @param validatable Validatable items.
   * @return The map of keys
   */
  @SuppressWarnings("unchecked")
  @Override
  protected Map variablesMap(IValidatable validatable) {
    Map map = super.variablesMap(validatable);
    return map;
  }
}